//
//  VipViewController.m
//  ProfilePicture
//
//  Created by 张云江 on 2019/10/17.
//  Copyright © 2019年 张云江. All rights reserved.
//

#import "VipViewController.h"
#import "SDCycleScrollView.h"

@interface VipViewController () <YQInAppPurchaseToolDelegate>
{
    ZHProgressHUD  *progressHUD;
}
@end

@implementation VipViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
}

- (void)setNav
{
    self.customNavBar.title = @"VIP会员";
}

- (void)creatUI
{
    UILabel *titleLabel = [[UILabel alloc] init];
    [self.view addSubview:titleLabel];
    titleLabel.font = [UIFont fontWithName:@"PingFang-SC-Medium" size:kRatio(21)];
    titleLabel.textColor = kUIColorFromRGB(0x000000);
    titleLabel.numberOfLines = 0;
    titleLabel.text = [NSString stringWithFormat:@"证件照Pro\n开通会员解锁全部功能"];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(kRatio(20));
        make.top.equalTo(self.view).offset(kRatio(24) + kNavigationHeight);
    }];
    
    NSArray *images = @[[UIImage imageNamed:@"vip_1"],[UIImage imageNamed:@"vip_2"],[UIImage imageNamed:@"vip_3"]];
    SDCycleScrollView *cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, kRatio(80) + kNavigationHeight, kScreenWidth, kRatio(236)) imageNamesGroup:images];
    cycleScrollView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:cycleScrollView];
    cycleScrollView.showPageControl = NO;
    
    UIButton *VipBtn = [[UIButton alloc]init];
    [VipBtn setTitle:[NSString stringWithFormat:@"立即开通高级VIP会员"] forState:UIControlStateNormal];
    [VipBtn addTarget:self action:@selector(onVipBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [VipBtn setBackgroundColor:kUIColorFromRGB(0x2F54EB)];
    VipBtn.layer.cornerRadius = 5;
    VipBtn.layer.masksToBounds = YES;
    [self.view addSubview:VipBtn];
    [VipBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(cycleScrollView.mas_bottom).offset(kRatio(10));
        make.width.mas_equalTo(kScreenWidth - kRatio(40));
        make.centerX.equalTo(self.view.mas_centerX);
        make.height.mas_equalTo(kRatio(47));
    }];
    
    UILabel *prelab = [[UILabel alloc]init];
    prelab.text = [NSString stringWithFormat:@"30元/月"];
    prelab.textColor = kUIColorFromRGA(0x000000, 0.4);
    prelab.font = [UIFont systemFontOfSize:kRatio(14)];
    [self.view addSubview:prelab];
    [prelab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.top.equalTo(VipBtn.mas_bottom).offset(kRatio(12));
    }];
    
    UILabel *describeLabel = [[UILabel alloc] init];
    describeLabel.numberOfLines = 0;
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.firstLineHeadIndent = kRatio(9) * 2;
    NSMutableAttributedString *describeString = [[NSMutableAttributedString alloc] initWithString:@"关于自动续费的声明\n付款：自动续费商品在您确定购买后，会从您的苹果iTunes账户扣费；\n续费会员：您订阅的清爽视频编辑器会员到期前24小时，苹果会自动为您从iTunes账号扣除相应费用，成功后清爽视频编辑器会员服务自动延长一个周期；\n取消续费：若需要取消自动续费，请在订阅周期结束前至少24小时关闭自动续订，关闭后不再扣费；若未在到期前24小时取消，将自动续订；\n取消方法：从Home页进入『设置』→『iTunes Store与App Store』→选择『Apple ID』→点击『查看Apple ID』→在账户设置页面点击『订阅』→选择应用取消订阅即可。" attributes:@{NSFontAttributeName:[UIFont fontWithName:@"PingFang-SC-Regular" size: kRatio(9)],NSParagraphStyleAttributeName:paragraphStyle,NSForegroundColorAttributeName:kUIColorFromRGA(0x000000, 0.4)}];
    describeLabel.attributedText = describeString;
    
    [self.view addSubview:describeLabel];
    [describeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(prelab.mas_bottom).offset(kRatio(10));
        make.width.mas_equalTo(kScreenWidth - kRatio(40));
        make.centerX.equalTo(self.view.mas_centerX);
    }];
    
    NSMutableArray *btnItemTemp3 = [NSMutableArray array];
    
    UILabel *termsLabel = [[UILabel alloc] init];
    NSMutableAttributedString *termsString = [[NSMutableAttributedString alloc] initWithString:NSLocalizedString(@"服务条款", nil) attributes:@{NSFontAttributeName: [UIFont fontWithName:@"PingFang-SC-Regular" size: kRatio(10)],NSForegroundColorAttributeName: [UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1.0],NSUnderlineStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]}];
    termsLabel.attributedText = termsString;
    [self.view addSubview:termsLabel];
    [btnItemTemp3 addObject:termsLabel];
    
    UILabel *policyLabel = [[UILabel alloc] init];
    NSMutableAttributedString *policyString = [[NSMutableAttributedString alloc] initWithString:NSLocalizedString(@"隐私政策", nil) attributes:@{NSFontAttributeName: [UIFont fontWithName:@"PingFang-SC-Regular" size: kRatio(10)],NSForegroundColorAttributeName: [UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1.0],NSUnderlineStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]}];
    policyLabel.attributedText = policyString;
    [self.view addSubview:policyLabel];
    [btnItemTemp3 addObject:policyLabel];
    
    UILabel *buyLabel = [[UILabel alloc] init];
    NSMutableAttributedString *buyString = [[NSMutableAttributedString alloc] initWithString:NSLocalizedString(@"恢复购买", nil) attributes:@{NSFontAttributeName: [UIFont fontWithName:@"PingFang-SC-Regular" size: kRatio(10)],NSForegroundColorAttributeName: [UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1.0],NSUnderlineStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]}];
    buyLabel.attributedText = buyString;
    [self.view addSubview:buyLabel];
    [btnItemTemp3 addObject:buyLabel];
    
    termsLabel.tag = 2;
    policyLabel.tag = 3;
    buyLabel.tag = 4;
    
    termsLabel.userInteractionEnabled = YES;
    policyLabel.userInteractionEnabled = YES;
    buyLabel.userInteractionEnabled = YES;
    
    [termsLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTap:)]];
    [policyLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTap:)]];
    [buyLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTap:)]];
    
    [btnItemTemp3 mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:kRatio(40) leadSpacing:kRatio(70) tailSpacing:kRatio(70)];
    
    [btnItemTemp3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view.mas_bottom).offset(kRatio(-21));
    }];
}

- (void)didTap:(UITapGestureRecognizer *)sender
{
    NSInteger index = sender.view.tag;
    switch (index) {
        case 2:
        {
            WebViewController *webVc = [[WebViewController alloc] init];
            webVc.titles = @"服务条款";
            webVc.requestFullURL = kTermsofUse;
            [self.navigationController pushViewController:webVc animated:YES];
        }
            break;
        case 3:
        {
            WebViewController *webVc = [[WebViewController alloc] init];
            webVc.titles = @"隐私政策";
            webVc.requestFullURL = kPrivacyPolicy;
            [self.navigationController pushViewController:webVc animated:YES];
        }
            break;
        case 4:
        {
            [self restoreProduct];
        }
            break;
            
        default:
            break;
    }
}

- (void)onVipBtnClick
{
    YQInAppPurchaseTool *IAPTool = [YQInAppPurchaseTool defaultTool];
    IAPTool.delegate = self;
    [IAPTool requestProductsWithProductArray:@[@"com.yhjy.ProfilePicture_new_1"]];
    
    progressHUD = [ZHProgressHUD showMessage:@"正在购买"];
    [self performSelector:@selector(onJoinFailed) withObject:nil afterDelay:20.0f];
}

#pragma mark - YQInAppPurchaseToolDelegate
- (void)IAPToolGotProducts:(NSMutableArray *)products {
    NSLog(@"商品信息 = %@",[[products firstObject] mj_keyValues]);
    if (products.count > 0) {
        [self BuyProduct:[products firstObject]];
    } else {
        [ZHProgressHUD hideHUD];
        [MBProgressHUD showError:@"商品信息不存在"];
    }
}

//购买商品
- (void)BuyProduct:(SKProduct *)product
{
    [[YQInAppPurchaseTool defaultTool] buyProduct:product.productIdentifier];
}

//取消购买
- (void)IAPToolCanceldWithProductID:(NSString *)productID
{
    NSLog(@"取消购买==%@",productID);
    [MBProgressHUD hideHUD];
    [ZHProgressHUD hideHUD];
}

//购买成功，开始验证购买
- (void)IAPToolBeginCheckingdWithProductID:(NSString *)productID
{
    NSLog(@"BeginChecking:%@",productID);
    progressHUD = [ZHProgressHUD showMessage:@"正在购买"];
    [self performSelector:@selector(onJoinFailed) withObject:nil afterDelay:20.0f];
}

//验证失败
- (void)IAPToolCheckFailedWithProductID:(NSString *)productID andInfo:(NSData *)infoData
{
    NSLog(@"CheckFailed:%@",productID);
    [ZHProgressHUD hideHUD];
    [MBProgressHUD showError:@"验证失败"];
}

//重复验证
- (void)IAPToolCheckRedundantWithProductID:(NSString *)productID {
    NSLog(@"CheckRedundant:%@",productID);
    [ZHProgressHUD hideHUD];
    [MBProgressHUD showError:@"重复验证"];
}

//购买成功
- (void)IAPToolBoughtProductSuccessedWithProductID:(NSString *)productID andInfo:(NSDictionary *)infoDic
{
    NSLog(@"BoughtSuccessed:%@",productID);
    NSLog(@"successedInfo:%@",infoDic);
    [ZHProgressHUD hideHUD];
    [MBProgressHUD showSuccess:@"购买成功"];
    
    [self vipDeadlineProductID:productID];
    
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"vipBool"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    if (self.navigationController) {
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

//恢复已购买的商品
- (void)restoreProduct
{
    progressHUD = [ZHProgressHUD showMessage:@"正在恢复商品"];
    [self performSelector:@selector(onJoinFailed) withObject:nil afterDelay:20.0f];
    [[YQInAppPurchaseTool defaultTool] restorePurchase];
}

//恢复了已购买的商品（仅限永久有效商品）
- (void)IAPToolRestoredProductID:(NSString *)productID
{
    NSLog(@"Restored:%@",productID);
    [ZHProgressHUD hideHUD];
    [MBProgressHUD showSuccess:@"成功恢复了商品"];
    
    [self vipDeadlineProductID:productID];
    
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"vipBool"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    if (self.navigationController) {
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)vipDeadlineProductID:(NSString *)productID
{
    NSString *date;
    if ([productID isEqualToString:@"com.yhjy.ProfilePicture_new_1"]) {
        date = [self getNDay:[NSDate daysInMonthFromDate:[NSDate date]]];
        [[NSUserDefaults standardUserDefaults] setObject:date forKey:@"Date"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}

- (NSString *)getNDay:(NSInteger)n
{
    NSDate *nowDate = [NSDate date];
    NSDate *theDate;
    if (n != 0) {
        NSTimeInterval  oneDay = 24*60*60*1;
        theDate = [nowDate initWithTimeIntervalSinceNow: oneDay*n ];
    } else {
        theDate = nowDate;
    }
    NSDateFormatter *date_formatter = [[NSDateFormatter alloc] init];
    [date_formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *the_date_str = [date_formatter stringFromDate:theDate];
    return the_date_str;
}

- (void)onJoinFailed
{
    [progressHUD hideHUD];
}
@end
